#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string>
#include <string.h>
#include <stdio.h>
#include "tcp_sever.hpp"

using namespace std;

int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        cout<<"请输入三个参数："<<argv[0]<<"，ip地址，端口号"<<endl;
        exit(1);
    }
    //创建套接字
    int clientsocket = socket(AF_INET,SOCK_STREAM,0);
    if(clientsocket < 0)
    {
        logMassage(FATAL, "创建套接字失败：%d : %s\n", errno, strerror(errno));
        exit(2);
    }
    struct sockaddr_in src;
    memset(&src,0,sizeof src);
    src.sin_family = AF_INET;
    src.sin_port = htons(atoi(argv[2]));
    src.sin_addr.s_addr = inet_addr(argv[1]);
    if(connect(clientsocket,(struct sockaddr*)&src,sizeof src) < 0)
    {
        logMassage(FATAL, "连接失败：%d : %s\n", errno, strerror(errno));
        exit(5);
    }
    //走到这里 说明连接成功了
    logMassage(NORMAL,"连接成功\n");
    while(1)
    {
        string buffer;
        cout<<"请输入信息：";
        getline(cin,buffer);
        if(buffer.size() == 0)
        {
            printf("不能发送空消息\n");
            continue;
        }
        send(clientsocket,buffer.c_str(),buffer.size(),0);
        char recbuffer[1024];
        ssize_t s = recv(clientsocket,recbuffer,sizeof recbuffer - 1,0);
        if(s > 0)//正常接收
        {
            recbuffer[s] = '\0';
            printf("服务器发回：%s\n",recbuffer);
        }
        else if(s == 0)//服务器关闭了
        {
            logMassage(ERROR,"服务器关闭\n");
            break;
        }
        else//出现错误了
        {
            logMassage(FATAL,"从服务器读取数据出错\n");
            break;
        }
        
    }
    close(clientsocket);
    return 0;
}